import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/question.dart';
import '../models/answer.dart';

class ApiService {
  static const String baseUrl = 'https://www.mxnzp.com/api/driver_exam';
  static const String appId = 'jijnkniwlmswemjf';
  static const String appSecret = 'og1FoKNxT0IJMZNdb1UYkcidZBwTjgeE';

  final http.Client _client = http.Client();
  final Duration _timeout = const Duration(seconds: 15);

  // 获取题目列表
  Future<Map<String, dynamic>> getQuestions(
      int page, int rank, int type) async {
    final url = Uri.parse(
        '$baseUrl/question/list?page=$page&rank=$rank&type=$type&app_id=$appId&app_secret=$appSecret');

    try {
      final response = await _client.get(url).timeout(_timeout);

      if (response.statusCode == 200) {
        final Map<String, dynamic> data = json.decode(response.body);

        if (data['code'] == 1) {
          final questionData = data['data'];
          final List<dynamic> questionList = questionData['list'];

          final questions =
              questionList.map((item) => Question.fromJson(item)).toList();

          return {
            'questions': questions,
            'totalPage': questionData['totalPage'],
            'currentPage': questionData['page'],
            'totalCount': questionData['totalCount'],
          };
        } else {
          throw Exception('获取题目失败: ${data['msg']}');
        }
      } else {
        throw Exception('网络请求失败: ${response.statusCode}');
      }
    } on TimeoutException {
      throw Exception('请求超时，请检查网络连接');
    } catch (e) {
      throw Exception('网络请求失败: $e');
    }
  }

  // 获取答案和解析
  Future<List<Answer>> getAnswers(List<int> ids) async {
    final idsString = ids.join(',');
    final url = Uri.parse(
        '$baseUrl/answer/list?ids=$idsString&app_id=$appId&app_secret=$appSecret');

    final response = await http.get(url);

    if (response.statusCode == 200) {
      final Map<String, dynamic> data = json.decode(response.body);

      if (data['code'] == 1) {
        final List<dynamic> answerList = data['data'];
        return answerList.map((item) => Answer.fromJson(item)).toList();
      } else {
        throw Exception('获取答案失败: ${data['msg']}');
      }
    } else {
      throw Exception('网络请求失败: ${response.statusCode}');
    }
  }
}
